//
//  EditPhoneViewController.m
//  FactorySale
//
//  Created by 李 on 2020/1/16.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "EditPhoneViewController.h"
#import "LMCountDownButton.h"

@interface EditPhoneViewController ()
@property (nonatomic,strong)UITextField *phoneTF;
@property (nonatomic,strong)UITextField *yanZhengMaTF;

@end

@implementation EditPhoneViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"修改联系方式";
    [self configViews];
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
}

-(void)configViews{
    //联系方式
    _phoneTF = [[UITextField alloc] init];
    _phoneTF.placeholder = @"请输入联系电话";
    _phoneTF.font = FontSize(14);
    _phoneTF.textColor = [UIColor colorWithHexString:@"#333333"];
    _phoneTF.textAlignment = NSTextAlignmentLeft;
    _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    [_phoneTF addTarget:self action:@selector(phonetextFieldDidChange:)  forControlEvents:UIControlEventEditingChanged]; //手机号限制11位
    [self.view addSubview:_phoneTF];
    [_phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kNaviHeight);
        make.left.equalTo(self.view.mas_left).offset(20);
        make.width.offset(200);
        make.height.offset(44);
    }];
    
    LMCountDownButton *sendCodeButton = [[LMCountDownButton alloc] init];
    [sendCodeButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    [sendCodeButton setTitleColor:zhutiColor forState:(UIControlStateNormal)];
    sendCodeButton.titleLabel.font = FontSize(11);
    [sendCodeButton addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    sendCodeButton.layer.cornerRadius = 5;
    sendCodeButton.clipsToBounds = YES;
    sendCodeButton.layer.borderWidth = 1;
    sendCodeButton.layer.borderColor = zhutiColor.CGColor;
    sendCodeButton.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:sendCodeButton];
    [sendCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_phoneTF);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.width.offset(90);
        make.height.offset(30);
    }];
    
    //分割线
    UILabel *line = [[UILabel alloc] init];
    line.backgroundColor = [UIColor colorWithHexString:@"#E5E5E5"];
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_phoneTF.mas_bottom);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.offset(1);
    }];
    
    
    //验证码
    _yanZhengMaTF = [[UITextField alloc] init];
    _yanZhengMaTF.placeholder = @"请输入6位短信验证码";
    _yanZhengMaTF.font = FontSize(14);
    _yanZhengMaTF.textColor = [UIColor colorWithHexString:@"#333333"];
    _yanZhengMaTF.textAlignment = NSTextAlignmentLeft;
    _yanZhengMaTF.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:_yanZhengMaTF];
    [_yanZhengMaTF addTarget:self action:@selector(vericodetextFieldDidChange:)  forControlEvents:UIControlEventEditingChanged]; //验证码限制6位
    [_yanZhengMaTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(line.mas_bottom);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.offset(44);
    }];
    
    //分割线
    UILabel *line2 = [[UILabel alloc] initWithFrame:CGRectMake(20, _yanZhengMaTF.bottom, ScreenW -20 * 2, 0.5)];
    line2.backgroundColor = [UIColor colorWithHexString:@"#E5E5E5"];
    [self.view addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_yanZhengMaTF.mas_bottom);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.offset(1);
    }];
    
    //确定
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    btn.titleLabel.font = FontSize(15);
    btn.backgroundColor = zhutiColor;
    btn.layer.cornerRadius = 5;
    btn.clipsToBounds = YES;
    [btn addTarget:self action:@selector(sureBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(line2.mas_bottom).offset(45);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.offset(44);
    }];
}

-(void)sureBtnClick:(UIButton *)sender
{
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    
    param[@"phone"] = _phoneTF.text;
    param[@"yzCode"] = _yanZhengMaTF.text;
    
    //去除字符串中空格
    _phoneTF.text = [_phoneTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (![self isMobileNumberOnly:_phoneTF.text]) {
        ShowToastWithText(@"请输入正确的手机号");
        return;
    }
    
    if ([_yanZhengMaTF.text isEqualToString:@""]) {
        ShowToastWithText(@"验证码不能为空");
        return;
    }
    
    if (_yanZhengMaTF.text.length < 6) {
        ShowToastWithText(@"请输入正确的验证码");
        return;
    }
    [MBProgressHUD showHUDAddedTo:self.view  animated:YES];

    [NetWorkTool POST:checkFactoryPhone param:param success:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSString *errcode = [NSString stringWithFormat:@"%@",dic[@"errorCode"]];
        if ([errcode isEqualToString:@"0"]) {
            self.phoneEditHandle(self->_phoneTF.text);
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            NSString *msg = dic[@"msg"];
            ShowToastWithText(msg);
        }
    } other:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        ShowToastWithText(dic[@"msg"]);
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } needUser:NO];
}

-(void)click:(LMCountDownButton *)sender {
    //去除字符串中空格
    _phoneTF.text = [_phoneTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (![self isMobileNumberOnly:_phoneTF.text]) {
        ShowToastWithText(@"请输入正确电话号码");
        return;
    }
    NSDictionary *dic = @{@"phone":_phoneTF.text};
    [MBProgressHUD showHUDAddedTo:self.view  animated:YES];

    [NetWorkTool POST:sendMsg param:[dic mutableCopy] success:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [sender startCountDown];
        ShowToastWithText(@"验证码发送成功");
    } other:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } needUser:NO];
}

///判断是否为电话号码
- (BOOL)isMobileNumberOnly:(NSString *)mobileNum {
    
    NSString * MOBILE = @"^((10[0-9])|(11[0-9])|(12[0-9])|(13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    if ([regextestmobile evaluateWithObject:mobileNum] == YES) {
        return YES;
    } else {
        return NO;
    }
}

//手机号码 限制输入11位
- (void)phonetextFieldDidChange:(UITextField *)textField {
    NSString *toBeString = textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    CGFloat maxLength = 11;
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position){
        if (toBeString.length > maxLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1){
                textField.text = [toBeString substringToIndex:maxLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

//验证码 限制输入6位
- (void)vericodetextFieldDidChange:(UITextField *)textField {
    NSString *toBeString = textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    CGFloat maxLength = 6;
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position){
        if (toBeString.length > maxLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1){
                textField.text = [toBeString substringToIndex:maxLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

@end
